<template>
  <div>
    <el-card class="doctor">
      <el-form :model="searchForm" ref="searchRef" inline class="search">
        <el-form-item label="医生昵称" prop="doctorNickname">
          <el-select
            v-model="searchForm.doctorNickname"
            placeholder="请选择医生昵称"
            class="form_input"
            filterable
          >
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :labe="item.doctorNickname"
              :value="item.doctorNickname"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button icon="search" type="primary" @click="getList()">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt-1">
      <div class="w-full flex justify-end items-center">
        <el-button type="primary" icon="Plus" @click="handleEdit({ id: 0 })"
          >医生授权码</el-button
        >
      </div>

      <el-table :data="tableData" class="doctor-data">
        <el-table-column label="医生账号" prop="doctorUsername" />
        <el-table-column label="医生昵称" prop="doctorNickname" />
        <el-table-column label="设备编号" prop="deviceSn" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status == 1 ? 'primary' : 'danger'">
              {{ row.status == 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="授权到期时间">
          <template #default="{ row }">
            {{ $initTime(row.authExpireTime * 1000) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="{ row }">
            <div class="w-full flex flex-col justify-between items-center">
              <el-button
                type="warning"
                class="w-full"
                @click="handleStatus(row)"
              >
                <el-icon v-if="row.status == 2"><Select /></el-icon>
                <el-icon v-else><Close /></el-icon>
                {{ row.status == 1 ? "禁用" : "启用" }}
              </el-button>
              <el-button
                type="primary"
                class="w-full mt-1"
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
                修改授权时间
              </el-button>

              <el-button
                type="danger"
                class="w-full mt-1"
                @click="handleRemove(row.id)"
              >
                <el-icon><delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <PagingQuery
        :page="page"
        :size="size"
        :total="total"
        @getList="getList"
        class="mt-2"
      />
    </el-card>

    <el-drawer
      v-model="drawer"
      :title="detailForm.id == 0 ? '绑定医生账号' : '修改授权时间'"
      size="35%"
      destroy-on-close
    >
      <AuthorizationCode
        :detailForm="detailForm"
        :form="form"
        :doctorList="doctorList"
        @handleBack="handleBack"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import PagingQuery from "@/components/PagingQuery.vue";
import AuthorizationCode from "./AuthorizationCode.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  ListCooperativeDoctorsAll,
  ListMqttAuthCodes,
  DeleteMqttAuthCode,
  UpdateMqttAuthCodeStatus,
} from "../../../../../wailsjs/go/api/DeviceApi";

onMounted(() => {
  getList();
  getDoctorList();
});

const props = defineProps({
  detailForm: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const searchRef = ref(null);
const searchForm = ref({
  doctorUsername: "",
  doctorNickname: "",
});
const handleReset = () => {
  searchRef.value.resetFields();
  getList();
};

const page = ref(1);
const size = ref(10);
const total = ref(0);
const tableData = ref([]);
async function getList(e) {
  if (e) {
    page.value = e.page;
    size.value = e.size;
  }

  handleApiResponse(() =>
    ListMqttAuthCodes({
      deviceSn: props.detailForm.deviceSn,
      page: page.value,
      size: size.value,
      ...searchForm.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  });
}
// 1.启用禁用
const handleStatus = (row) => {
  let title = `你确定要${row.status == 1 ? "禁用" : "启用"}该账号长期授权吗`;
  ElMessageBox.confirm(title, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      UpdateMqttAuthCodeStatus({
        id: row.id,
        status: row.status == 1 ? 2 : 1,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("操作成功");
        getList();
      }
    });
  });
};

// 2.修改授权时间
const drawer = ref(false);
const form = ref({});
const handleEdit = (row) => {
  form.value = cloneDeep(row);
  drawer.value = true;
};
const handleBack = (val) => {
  if (val == 1) {
    getList();
  }
  form.value = {};
  drawer.value = false;
};
// 3.删除
const handleRemove = (id) => {
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() => DeleteMqttAuthCode({ id: id })).then((res) => {
      if (res.code == 0) {
        ElMessage.success("删除成功");
        getList();
      }
    });
  });
};

const doctorList = ref([]);
async function getDoctorList() {
  handleApiResponse(() => ListCooperativeDoctorsAll({})).then((res) => {
    if (res.code == 0) {
      //   console.log(res);
      doctorList.value = res.data.list || [];
    }
  });
}
</script>

<style scoped lang="scss">
.doctor .el-form-item {
  @apply mb-1;
}
.doctor-data {
  height: calc(100vh - 15rem);
  .el-button + .el-button {
    @apply ml-0;
  }
}
</style>